// 商品回收站
import React, { useState, useEffect } from 'react';
import { Table, Image, Space, Button, Form, Collapse, Input, Select, Modal, message, ConfigProvider } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ExclamationCircleFilled } from '@ant-design/icons';
import zh_CN from 'antd/es/locale/zh_CN';
import '../../css/operation.css'
import { getGoodRecycle, getCategory, getGoodBrand, delGoodRecycle } from '../../../api/opreationApi'
// 表格
interface DataType {
  key: React.Key
  goodsId: number
  brandName: string //品牌名称
  categoryName: string //分类名称
  goodsImg: string //商品图片
  goodsName: string //商品名称
  goodsPriceRange: string //价格
  goodsSernum: string//货号                                                                                              
}

export default function GoodRecycle() {
  const [recycleData, setRecycleData] = useState<DataType[]>([])//当前页渲染数据
  const [page, setPage] = useState<number>(1) //当前第几页 
  const [limit, setLimit] = useState<number>(5) //每页条数
  const [total, setTotal] = useState<number>()//总条数
  const [goodsName, setGoodsName] = useState<string>()//关键字
  const [goodsBrandId, setGoodsBrandId] = useState<number>()//选择品牌
  const [goodsCategoryId, setGoodsCategoryId] = useState<number>()//选择类型
  const [type, setType] = useState<any>()//分类下拉数据
  const [brand, setBrand] = useState<any>()//品牌下拉数据
  const [selectedRow, setSelectedRow] = useState<DataType[]>([]);//多选选中的数据
  const [goodsStatus, setGoodsStatus] = useState<string>('6')//查询状态
  // 拿初始数据、查询、排序
  const getData = () => {
    getGoodRecycle({
      limit, page, goodsStatus, goodsBrandId, goodsName, goodsCategoryId
    }).then(res => {
      if (~~res.code === 200) {
        setRecycleData(res.data.data)
        setTotal(res.data.totalByStatus)
      } else {
        setRecycleData([])
        setTotal(0)
      }
      setGoodsStatus('6')
    })
  }

  useEffect(() => {
    getData()
  }, [limit, page, brand, goodsBrandId, goodsName, goodsCategoryId])

  //页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
  const pageChange = (page: number, pageSize: number) => {
    setPage(page)
    setLimit(pageSize)
  }

  // 查询品牌和查询分级信息
  useEffect(() => {
    getGoodBrand().then(res => {
      let brand = res.data.map((item:any) => ({
        label: item.brandName,
        value: item.brandId
      }))
      setBrand(brand)
    })
    getCategory().then(res => {
      console.log(res);
      let type = res.data.map((item:any) => ({
        label: item.categoryName,
        value: item.categoryId
      }))
      setType(type)
    })
  }, [])


  const { Panel } = Collapse;
  // 表格
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[], row: DataType[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    setSelectedRow(row)
  };
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'goodsId',
    },
    {
      title: '封面图',
      dataIndex: 'goodsImg',
      render: (_, record) => (
        <Image
          width={70}
          height={50}
          src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
        />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '货号',
      dataIndex: 'goodsSernum',
    },
    {
      title: '价格',
      dataIndex: 'goodsPriceRange',
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
    },
    {
      title: '操作',
      dataIndex: 'address',
      render: (_, record) => (
        <Space size="middle">
          <Button className='add' onClick={() => restore(record)}>还原</Button>
          <Button id='del' onClick={() => showConfirm(record)}>永久删除</Button>
        </Space >
      ),
    },
  ];

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  const [form] = Form.useForm();//使用From表单，用于默认值
  // 操作部分
  // （1）删除
  // 删除弹框
  const { confirm } = Modal;
  const showConfirm = (record: any) => {
    confirm({
      title: '提示:',
      icon: <ExclamationCircleFilled />,
      content: '您确定要删除吗？删除后无法恢复！',
      cancelText: '取消',
      okText: '确认',
      onOk() {
        setGoodsStatus('6')
        // 点击确定发起请求
        if (Array.isArray(record)) {
          let goodsId = selectedRow.map(item => item.goodsId)
          delGoodRecycle(goodsId).then(res => {
            getData()
          })
        } else {
          delGoodRecycle([record.goodsId]).then(res => {
            getData()
          })
        }
        message.success('删除成功！')
      },
    });
  };
  // （2）还原
  const restore = (record: any) => {
    message.success('还原成功！')
    delGoodRecycle([record.goodsId]).then(res => {
      getData()
    })
  }

  // (3)查询按钮
  const sreach = (values: any) => {
    setGoodsName(values.goodsName)
    setGoodsBrandId(values.brandName)
    setGoodsCategoryId(values.type)
    message.success('查询成功！')
  }

  //（4） 重置按钮
  const reset = () => {
    getGoodRecycle({
      limit, page, goodsStatus
    }).then(res => {
      console.log(res);
      setRecycleData(res.data.data)
      setTotal(res.data.totalByStatus)
      setGoodsStatus('6')
    })
    form.resetFields()
    message.success('重置成功！')
  }

  // （5）批量删除
  const batchdel = () => {
    // 判断用户是否选择
    if (selectedRowKeys.length > 0) {
      showConfirm(selectedRowKeys)
    } else {
      message.error('请选择删除商品！')
    }
  }

  // 批量还原
  const batchOrigin = () => {
    if (selectedRowKeys.length > 0) {
      setGoodsStatus('5')
      let goodsId = selectedRow.map(item => item.goodsId)
      delGoodRecycle(goodsId).then(res => {
        getData()
      })
    } else {
      message.error('请选择还原商品！')
    }
  }

  return <div>
    {/* 头部标题 */}
    <p className='head'>商品回收站</p>
    {/* 筛选查询 */}
    {/* 搜索操作 */}
    <Collapse className='collapse' defaultActiveKey={['1']}>
      <Panel header="筛选查询" key="1">
        <div className='operate-wrap operate-left' id='operate-wrap'>
          {/* 搜索关键词 */}
          <Form form={form} className='operate-left' onFinish={sreach}>
            <Form.Item label="关键词：" className='operate-left-item' name='goodsName'>
              <Input placeholder=" 商品名称" className='search' />
            </Form.Item>
            {/* 商品分类 */}
            <Form.Item label='分类' className='operate-left-item' name='type'>
              <Select
                style={{ width: 120 }}
                allowClear
                options={type}
                className='drop'
                placeholder='请选择品牌'
              />
            </Form.Item>
            {/* 商品品牌 */}
            <Form.Item label='品牌' className='operate-left-item' name='brandName'>
              <Select
                style={{ width: 120 }}
                allowClear
                options={brand}
                className='drop'
                placeholder='请选择品牌'
              />
            </Form.Item>
            {/* 操作 */}
            <Form.Item>
              <Button className='inquire operate-left-item' htmlType='submit'>查询</Button>
              <Button className='reset operate-left-item' onClick={reset}>重置</Button>
            </Form.Item>
          </Form>
        </div>
      </Panel>
    </Collapse>
    {/* 表格列表整体 */}
    <div className='table'>
      {/* 表格操作 */}
      <div className='operationTable bottomItems' >
        <Button className='add operate-left-item' onClick={batchOrigin}>批量还原</Button>
        <Button id='del' onClick={batchdel}>批量永久删除</Button>
      </div>
      {/* 表格 */}
      <ConfigProvider locale={zh_CN}>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={recycleData}
          rowKey={item => recycleData.indexOf(item)}
          pagination={{
            position: ['bottomRight'],
            defaultPageSize: 5,
            pageSizeOptions: [2, 3, 5, 6],
            showQuickJumper: true,
            showSizeChanger: true,
            total: total,
            onChange: pageChange,
            pageSize: limit,
            showTotal: (total: number) => (`共有 ${total} 条数据`)
          }} />
      </ConfigProvider>
    </div>
  </div>
};
